//
//  BKUserMyCouponController.m
//  bestkeep
//
//  Created by windCould on 16/12/19.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKUserMyCouponController.h"
#import "BKMyCommon.h"
#import "SBJson.h"
#import "Mediator+BKGD.h"
#import "NJKWebViewProgressView.h"
#import "NJKWebViewProgress.h"
#import "Mediator.h"

@interface BKUserMyCouponController ()<UIWebViewDelegate, NJKWebViewProgressDelegate>

@property (nonatomic,strong)UIWebView * webView;
@property (nonatomic,strong)NSURLRequest * request;
@property (nonatomic,strong)NJKWebViewProgressView *progressView;
@property (nonatomic,strong)NJKWebViewProgress *progressProxy;
@property (nonatomic,assign)BOOL isAuth;
@property (nonatomic,strong) NSURLConnection *urlConnection;

@end

@implementation BKUserMyCouponController

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_progressView removeFromSuperview];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.title = @"我的会员卡";
    CGFloat progressBarHeight = 2.f;
    CGRect navigationBarBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0, navigationBarBounds.size.height - progressBarHeight, navigationBarBounds.size.width, progressBarHeight);
    
    //进度条
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    _progressProxy = [[NJKWebViewProgress alloc] init];
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
   
    //创建webview
    _webView = [UIWebView new];
    _webView.delegate= _progressProxy;
    _webView.scalesPageToFit = YES;
    _webView.backgroundColor = [UIColor clearColor];
    _webView.scrollView.directionalLockEnabled = NO;
    NSURL* url = [NSURL URLWithString:self.requestUrl];
    _request = [NSURLRequest requestWithURL:url];
    [_webView loadRequest:_request];
    [self.view addSubview:_webView];
    _webView.scrollView.bounces = NO;
    [self layoutViews];
    
    for (UIView *sbview in [_webView subviews])
    {
        if ([sbview isKindOfClass:[UIScrollView class]])
        {
            [(UIScrollView *)sbview setShowsVerticalScrollIndicator:NO];
        }
    }
    
    [self setNavBtn];
    [self.navigationController.navigationBar addSubview:_progressView];
}


-(void)layoutViews
{
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.view.mas_top).offset(0);
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.right.mas_equalTo(self.view.mas_right).offset(0);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(0);
    }];
    

}

-(void)setNavBtn
{
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 32, 18);
    [leftBtn setImage:[UIImage imageNamed:@"RootNavigationBack"] forState:UIControlStateNormal];
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:@selector(goBack)];
    space.width = -16;
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    [leftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItems = @[space, leftItem];
}

#pragma mark =========================NJKWebViewProgressDelegate========================

-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [_progressView setProgress:progress animated:YES];
    NSString * tileStr  = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    if (tileStr == nil || [tileStr isEqualToString:@""]) {
        
        self.navigationItem.title = @"我的会员卡";
    } else {
    
        self.navigationItem.title = tileStr;
    }
}

-(void)goBack{
    
    if([_webView canGoBack]){
        [_webView goBack];
    }else{
        _webView.delegate = nil;
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

//准备加载内容时调用的方法，通过返回值来进行是否加载的设置
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
   
    NSString *requestString = [[request URL]absoluteString];
    requestString = [requestString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self shouldStartLoadWithRequest:requestString];
    return YES;
}

//开始加载时调用的方法
- (void)webViewDidStartLoad:(UIWebView *)webView{
   
    [BKIndicationView showInView:self.view];
    NSLog(@"开始加载时调用的方法");
}

//结束加载时调用的方法
- (void)webViewDidFinishLoad:(UIWebView *)webView{
   
    [BKIndicationView  dismiss];
    NSString * title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    self.title = title;
    NSLog(@"%@",title);
}

//加载失败时调用的方法
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
    NSLog(@"加载失败时调用的方法");
    [BKIndicationView dismiss];
   // [HUD showErrorMessage:@"加载失败"];
}

-(void)shouldStartLoadWithRequest:(NSString*)requestString{
    
    NSString *header = @"http://objc/";
    if ([requestString hasPrefix:header]) {
        
        BOOL shops = NO;
        NSArray *components = [requestString componentsSeparatedByString:@"http://objc/"];
        if (components.count > 1) {
            NSUInteger range = [requestString rangeOfString:@"{"].location;
            NSString *b = [requestString substringFromIndex:range];
            NSDictionary *param_dic = [b JSONValue];
            NSArray *widget = [param_dic objectForKey:@"widget"];
            if ([widget containsObject:@"shopcarbtn"] ) {
                shops = YES;
                
            }else if ([[param_dic objectForKey:@"action"] isEqualToString:@"open"]) {
                
                NSDictionary *goodsDic = param_dic[@"parameters"];
                UIViewController *goodsDetail = [[Mediator sharedInstance] BKGD_goodsDetailViewController:goodsDic[@"goodsNo"] saleTypes:nil];
                [self.navigationController pushViewController:goodsDetail animated:YES];
                
            }else if ([[param_dic objectForKey:@"action"] isEqualToString:@"close"]) {
                [self.navigationController popViewControllerAnimated:YES];
                
            }
            
        }
    }
}

#pragma mark =========================UrlConnectionDelegate===================================

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
{
 
    
    if ([challenge previousFailureCount] == 0)
    {
        _isAuth = YES;
        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
    } else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
{
    _isAuth =YES;
    [_webView loadRequest:_request];
    [_urlConnection cancel];
}


- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([[[UIDevice currentDevice] systemVersion] compare:@"9.3.2"] == NSOrderedAscending) {
        
        
        if([_webView canGoBack]){
           
            [_webView goBack];
        }
    }
    
}

@end
